package cn.geminis.data.jpa.repository;

import cn.geminis.data.jpa.SpringContextUtils;
import cn.geminis.data.jpa.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface StudentRepository extends
        JpaRepository<Student, String>,
        JpaSpecificationExecutor<Student> {

    @Query("from Student s join fetch s.books")
    List<Student> hql();

    @Transactional
    default int update(Student student) {
        var entityManager = SpringContextUtils.getEntityManager();
        var criteriaBuilder = entityManager.getCriteriaBuilder();
        var criteriaUpdate = criteriaBuilder.createCriteriaUpdate(Student.class);
        var root = criteriaUpdate.from(Student.class);
        criteriaUpdate.set("name", student.getName());
        criteriaUpdate.where(criteriaBuilder.equal(root.get("id"), student.getId()));
        var query = entityManager.createQuery(criteriaUpdate);
        return query.executeUpdate();
    }
}
